#!/usr/bin/ruby

MAX=50
INTERVAL=0.25

def print_array( a )
  system "clear"
  MAX.downto(1) {
    |line|
    for v in a do
      print v>=line ? '|' : ' '
    end
    print "\n"
  }
  sleep INTERVAL
end

def compare( a, b )
  return a < b
end

a=ARGV.collect { |x| Integer(x) }
a=Array.new(MAX,MAX).collect { |x| Integer( rand() * x ) } if a.length() == 0

def merge( a, b )
  c=Array.new()
  while a.length() > 0 and b.length() > 0 do
    if compare( a[0], b[0] ) then
      c.push( a.shift() ) 
    else
      c.push( b.shift() ) 
    end
  end
  (c.concat(a)).concat(b)
  return c
end

def sub( array, i_beg, i_end )
  return Array.new() if i_end < 0
  return Array.new() if i_end - i_beg < 0
  return array[i_beg..i_end]
end

def mergesort( array, i_beg, i_end )
  return array if i_end - i_beg < 1
  n=(i_end-i_beg)/2
  array=mergesort(array,i_beg,i_beg+n)
  array=mergesort(array,i_beg+n+1,i_end)
  array=sub(array,0,i_beg-1)+
    merge(sub(array,i_beg,i_beg+n),
	  sub(array,i_beg+n+1,i_end))+
    sub(array,i_end+1,array.size()-1)
  print_array(array)
  return array
end

print_array( a )
a=mergesort( a, 0, a.size()-1 )
